﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Security;
using CRM_Web.Models;

namespace CRM_Web.Controllers
{
    [RoutePrefix("api")]
    public class LoginController : ApiController
    {
        // GET: api/Login
      [HttpPost]
        public IHttpActionResult login([FromBody] Users user)
        {
            using (CRMDBEntities db = new CRMDBEntities())
            {
                var list = db.Users.SingleOrDefault(p => p.LoginName == user.LoginName);
                if (list != null)
                {
                    if (list.Islockout ==1)
                    {
                        return Json(new { code = -1, msg = "该用户已经锁定" });
                    }
                    else
                    {
                    
                        if (user.Password == list.Password)
                        {
                            string token = list.Id.ToString();
                            FormsAuthentication.SetAuthCookie(token, true);
                            return Json(new { code = 0, msg = "登录成功！",token= token });
                        }
                        else
                        {
                            return Json(new { code = -1, msg = "密码错误！" });
                        }
                    }
                }
                else
                {
                    return Json(new { code = -1, msg = "用户名不错在" });
                }
                
            }
                
        }
        /// <summary>
        /// 修改密码处理
        /// </summary>
        /// <param name="pass"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult password([FromBody] pass pa)
        {
            using(CRMDBEntities db=new CRMDBEntities())
            {
                var user = db.Users.FirstOrDefault(p => p.Id == pa.Id);
                if (user != null)
                {
                    if (user.Password == pa.password)
                    {
                        user.Password = pa.newpassword;
                        int n = db.SaveChanges();
                        if (n > 0)
                        {
                            return Json(new { code = 0, msg = "密码修改成功！" });
                        }
                        else
                        {
                            return Json(new { code = -1,msg = "密码修改失败！" });
                        }
                    }
                    else
                    {
                        return Json(new { code = -1, msg = "原始密码输入不正确！" });
                    }
                }
                else
                {
                    return Json(new { code = -1, msg = "用户不存在！" });
                }
            }
        }


    }
}
